<?php

class ArticleController extends OController {
    
    public $defaultAction='admin';
    public $homeUrl;
    public $addNewUrl;
    public $cancelUrl;
    public $generateJsonUrl;
    
    private $_model;
    
    public function init(){
        parent::init();
        $this->homeUrl=$this->createUrl($this->id.'/'.$this->defaultAction);
        $this->addNewUrl=$this->createUrl($this->id.'/create');
        $this->generateJsonUrl=$this->createUrl($this->id.'/updatealljson');
        $this->breadcrumbs=array(
            Lang::t('article.list.page.title')=>array($this->defaultAction),
        );
    }
    
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Article');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }
    
    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Article('adminSearch');
        $model->unsetAttributes();  // clear any default values
        $params = Yii::app()->request->getParam(get_class($model));
        if ($params){
            $model->attributes=$params;
        }    

        $this->render('admin', array(
            'model' => $model,
            'dataProvider'=>$model->adminSearch(),
            'formConfig' => array(
                'id' => $this->formId,
                'enableAjaxValidation' => true,
                'enableClientValidation' => true,
                'clientOptions' => array(
                    'validateOnSubmit' => true,
                ),
            ),
        ));
    }

    public function actionCreate() {
        $model = new Article('adminCreate');
        $model->autoFill();
        $content=new Content('adminCreate');
        $content->autoFill($model);
        $content->validatorList->add(CValidator::createValidator('required', $content, 'title_'));
        
        $this->performAjaxValidation($model, $content);
        
        $params=Yii::app()->request->getParam(get_class($model));
        $contentParams=Yii::app()->request->getParam(get_class($content));
        if ($params && $contentParams) {
            $model->attributes=$params;
            $model->image_= CUploadedFile::getInstances($model, 'image_');
            
            $content->attributes=$contentParams;
            $content->validate();
            
            if(empty($model->buttonCssClass_)) $model->buttonCssClass_=$model->urlFormat($content->title_);
            $model->validate();
            
            if (!$model->hasErrors() && !$content->hasErrors() && $model->addRecord($content)) {
                $model->regenerateJson();
                $model->refresh();
                $this->setFlash('success', Lang::t('article.create.flash.success'));
                $this->redirect(array('update', 'id' => $model->id));
            } else {
                $this->setFlash('error', Lang::t('article.create.flash.fail'));
            }
        }

        $this->render('createForm', array(
            'article' => $model,
            'content'=>$content,
            'formConfig' => array(
                'id' => $this->formId,
                'enableAjaxValidation' => true,
                'enableClientValidation' => true,
                'clientOptions' => array(
                    'validateOnSubmit' => true,
                ),
                'htmlOptions' => array(
                    'enctype' => 'multipart/form-data',
                ),
                'focus' => array($content, 'title_'),
            ),
        ));
    }    
    
    public function actionUpdate($id) {
        $model = $this->loadModel($id);
        $model->scenario='adminUpdate';
        $model->autoFill();
        
        $content=empty($model->html)?new Content('adminCreate'):$model->html;
        $content->autoFill($model);
        $content->validatorList->add(CValidator::createValidator('required', $content, 'title_'));
        
        $this->performAjaxValidation($model, $content);

        $params=Yii::app()->request->getParam(get_class($model));
        $contentParams=Yii::app()->request->getParam(get_class($content));
        if ($params && $contentParams) {
            $model->attributes=$params;
            $model->image_= CUploadedFile::getInstances($model, 'image_');
            
            $content->attributes=$contentParams;
            $content->validate();
            
            if(empty($model->buttonCssClass_)) $model->buttonCssClass_=$model->urlFormat($content->title_);
            $model->validate();
            
            if (!$model->hasErrors() && !$content->hasErrors() && $model->updateRecord($content)) {
                $model->regenerateJson();
                //$model->refresh();
                $this->setFlash('success', Lang::t('article.update.flash.success'));
                $this->refresh();
            }else{
               $this->setFlash('error', Lang::t('article.update.flash.fail'));
               //if($this->debugMode) print_r($model->errors);
            }
        }

        $this->render('updateForm', array(
            'article' => $model,
            'content'=>$content,
            'formConfig' => array(
                'id' => $this->formId,
                'enableAjaxValidation' => true,
                'enableClientValidation' => true,
                'clientOptions' => array(
                    'validateOnSubmit' => true,
                ),
                'htmlOptions' => array(
                    'enctype' => 'multipart/form-data',
                ),
                'focus' => array($content, 'title_'),
            ),
        ));
    }
    
    public function actionView($id) {
        $this->render('view', array(
            'data' => $this->loadModel($id),
        ));
    }
    
    public function actionDelete($id) {
        $model=$this->loadModel($id);
        $model->scenario='adminDelete';
        if ($model->deleteRecord()) {
            $model->regenerateJson();
            $this->setFlash('success', Lang::t('article.delete.flash.success'));
        }else{
            $this->setFlash('error', Lang::t('article.delete.flash.fail'));
            //if($this->debugMode) print_r($model->errors);
        }

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        //if (!isset($_GET['ajax']))
            $this->redirect(array('admin'));
    }
    
    public function actionSort(){
        $count=0;
        $params=$_POST;
        $parent=isset($params['parent'])? $params['parent']:0;
        if(isset($params['sort']))
            foreach($params['sort'] as $position=>$id){
                $count+=Article::model()->updateToPosition($id, $position+1, $parent);
            }
        if($count){
            Article::model()->regenerateJson();
            echo 'success';
        }else{
            echo 'fail';
        }
    }
    
    public function actionUpdatealljson(){
        if(Article::model()->regenerateJson())
            $this->setFlash('success', Lang::t('article.generate.json.flash.success'));
        else
            $this->setFlash('warning', Lang::t('article.generate.json.flash.fail'));
        $this->redirect(Yii::app()->request->urlReferrer);
    }
    
    public function loadModel($id) {
        if ($this->_model === null) {
            if (!empty($id))
                $this->_model = Article::model()->accessible()->findByPk((int) $id);

            if ($this->_model === null)
                HttpStatus::code(404);
        }
        return $this->_model;
    }
    
}
